using ArticleManagementSystem.Api.Db;
using ArticleManagementSystem.Api.Entity;
using ArticleManagementSystem.Api.Params;
using ArticleManagementSystem.Api.Repostisory;
using Microsoft.AspNetCore.Mvc;
using ArticleManagementSystem.Api.Utils;
using Microsoft.EntityFrameworkCore;
using System.Collections;
using System.Dynamic;
using System.Linq;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System.Collections.Generic;

namespace ArticleManagementSystem.Api.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class ArticleController : ControllerBase
    {
        private readonly IRepostisory<Article> _articleRepostisory;
        private readonly IRepostisory<Imgs> _imgRepostisory;
        private readonly DataBase _context;
        private readonly IWebHostEnvironment _iWebHostEnvironment;

        public ArticleController(IRepostisory<Article> articleRepostisory, IRepostisory<Imgs> imgRepostisory, IWebHostEnvironment iWebHostEnvironment)
        {
            _context = new DataBase();
            _articleRepostisory = articleRepostisory;
            _imgRepostisory = imgRepostisory;
            _iWebHostEnvironment = iWebHostEnvironment;
        }


        /// <summary>
        /// 添加文章
        /// </summary>
        /// <param name="addArticle">添加文章需要的参数集合</param>
        /// <returns></returns>
        [HttpPost, Route("addarticle")]
        public dynamic PostArticleContent(AddArticle addArticle)
        {

            var UserId = addArticle.UserId;
            var ArticleContent = addArticle.ArticleContent.Trim();
            var ArticleDetails = addArticle.ArticleDetails.Trim();
            var ArticleTitle = addArticle.ArticleTitle.Trim();
            var ArticleType = addArticle.ArticleType.Trim();
            var ImgId = addArticle.ImgId;


            ArticleContent = HtmlOrUbb.HtmlToUBB(ArticleContent);

            // var b = HtmlOrUbb.UBBToHtml(a);

            if (string.IsNullOrEmpty(ArticleTitle))
            {
                return new
                {
                    code = 1000,
                    msg = "标题不能为空"
                };
            }

            if (string.IsNullOrEmpty(ArticleContent))
            {
                return new
                {
                    code = 1000,
                    msg = "发布内容不能为空"
                };
            }


            if (string.IsNullOrEmpty(ArticleType))
            {
                return new
                {
                    code = 1000,
                    msg = "请选择文章类型"
                };
            }

            // var file = Request.Form.Files;
            // var filePath = ImgsHelper.UpImgs(file, _iWebHostEnvironment, _imgRepostisory);
            // var imgRes = new Imgs
            // {
            //     ImgsPath = filePath
            // };
            // _imgRepostisory.Insert(imgRes);
            // var imgId = imgRes.Id;

            var res = new Article
            {
                Content = ArticleContent,
                UserId = UserId,
                ArticleDetails = ArticleDetails,
                Title = ArticleTitle,
                ArticleType = ArticleType,
                ImgId = ImgId
            };

            _articleRepostisory.Insert(res);
            res.Content = HtmlOrUbb.UBBToHtml(ArticleContent);

            return new
            {
                code = 200,
                msg = "插入成功",
                data = res
            };
        }

        //查询文章
        [HttpPost, Route("query")]
        public dynamic PostQuery(Myquery querys)
        {
            var querydata = querys.query;
            // var pageIndex = querys.PageIndex;
            // var pageSize = querys.PageSize;
            var articletype = querys.ArticleType;
            var article = _articleRepostisory.Table;
            dynamic resdata;

            var sqlQuery = from tableArticle in _context.Set<Article>()
                           join tableUsers in _context.Set<Users>()
                               on tableArticle.UserId equals tableUsers.Id into grouping
                           from tableUsers in grouping.DefaultIfEmpty()
                           select new { tableArticle, tableUsers };

            var table = from ImgsTable in _context.Set<Imgs>()
                        join UserArticleTable in sqlQuery
                        on ImgsTable.Id equals UserArticleTable.tableArticle.ImgId into grouping
                        from UserArticleTable in grouping.DefaultIfEmpty()
                        select new { ImgsTable, UserArticleTable };


            if (string.IsNullOrEmpty(articletype))
            {
                resdata = sqlQuery.Where(x => x.tableUsers.Username.Contains(querydata)
                || x.tableArticle.ArticleDetails.Contains(querydata)
                || x.tableArticle.ArticleType.Contains(querydata)
                || x.tableArticle.Title.Contains(querydata)
                ).ToList();
            }
            else
            {
                resdata = sqlQuery.Where(x => x.tableUsers.Username.Contains(querydata)
                || x.tableArticle.ArticleDetails.Contains(querydata)
                || x.tableArticle.ArticleType.Contains(querydata)
                || x.tableArticle.Title.Contains(querydata)
                ).ToList();
            }
            ArrayList arraylist = new ArrayList();
            foreach (var item in resdata)
            {
                var Articleid = item.tableArticle.Id;
                arraylist.Add(Articleid);
            }
            var resTable = ArticleSelectHelper.GetArticleMsg(arraylist, _context);
            var res = new
            {
                Code = 200,
                Data = resTable,
                Msg = "查询成功"
            };
            return res;
        }

        //更新文章
        [HttpPut("{id}")]
        public dynamic PutUpdataArticle(int id, AddArticle updateArticle)
        {

            var UserId = updateArticle.UserId;
            var ArticleContent = updateArticle.ArticleContent.Trim();
            var ArticleDetails = updateArticle.ArticleDetails.Trim();
            var ArticleTitle = updateArticle.ArticleTitle.Trim();
            var ArticleType = updateArticle.ArticleType.Trim();


            if (string.IsNullOrEmpty(ArticleContent))
            {
                return new
                {
                    code = 104,
                    data = "",
                    msg = "内容不能为空"
                };
            }


            if (string.IsNullOrEmpty(ArticleDetails))
            {
                return new
                {
                    code = 104,
                    data = "",
                    msg = "详情不能为空"
                };
            }


            if (string.IsNullOrEmpty(ArticleTitle))
            {
                return new
                {
                    code = 104,
                    data = "",
                    msg = "标题不能为空"
                };
            }

            if (string.IsNullOrEmpty(ArticleType))
            {
                return new
                {
                    code = 104,
                    data = "",
                    msg = "请至少选择一种类型"
                };
            }

            var art = _articleRepostisory.GetById(id);

            if (art == null)
            {
                return new
                {
                    code = 104,
                    data = "",
                    msg = "查无此书"
                };
            }

            art.Content = updateArticle.ArticleContent.Trim();
            art.ArticleDetails = updateArticle.ArticleDetails.Trim();
            art.UserId = updateArticle.UserId;
            art.ArticleType = updateArticle.ArticleType.Trim();
            art.Title = updateArticle.ArticleTitle.Trim();


            _articleRepostisory.Updated(art);

            return new
            {
                code = 200,
                data = art,
                msg = "更新成功"
            };
        }

        //删除文章
        [HttpDelete("{id}")]
        public dynamic DeleteArticle(int id)
        {
            _articleRepostisory.Deleted(id);

            return new
            {
                code = 200,
                data = "",
                msg = "删除成功"
            };
        }


        //获取文章
        [HttpGet, Route("GetArticle")]
        public dynamic GetArticles()
        {
            var articles = _context.article.OrderByDescending(x=>x.Id).ToList();
            var imgs = _context.imgs.ToList();
            var users = _context.users.ToList();

            // var list = new List<dynamic>();
            // foreach (var item in articles)
            // {
            //     var img = imgs.Where(x => x.Id == item.ImgId).FirstOrDefault();
            //     var user = users.Where(x => x.Id == item.UserId).FirstOrDefault();

            //     var tmp = new
            //     {
            //         Id = item.Id,
            //         item.Title,
            //         item.Content,
            //         item.ArticleDetails,
            //         item.UserId,
            //         item.ArticleType,
            //         item.CreatedTime,
            //         ImgPath = img != null ? img.ImgsPath : "",
            //         Username = user != null ? user.Username : ""
            //     };
            //     list.Add(tmp);
            // }

            ArrayList arraylist = new ArrayList();
            foreach (var item in articles)
            {
                var Articleid = item.Id;
                arraylist.Add(Articleid);
            }
            var restable = ArticleSelectHelper.GetArticleMsg(arraylist, _context);

            return JsonHelper.Serialize(new
            {
                Code = 1000,
                Data = restable,
                Msg = "获取成功"
            });

        }


        //通过id获取文章
        [HttpGet, Route("{id}/GetArticle")]
        public dynamic GetArticle(int id){
            var articles = _articleRepostisory.Table;
            var res = articles.Where(x=>x.Id == id).FirstOrDefault();

            return new {
                code = 200,
                data = res,
                msg = "获取成功"
            };
        }
    }
}